<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions"
              @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan"
              collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.deviceCode" placeholder="设备编码" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.deviceName" placeholder="设备名称" />
          </el-form-item>
          <el-form-item>
            <SelectTree placeholder="所属组织" :props="organProps" :options="organOptionData" :value="valueIdSelectOrgan"
              :clearable="isClearable" :accordion="isAccordion" @getValue="getValueIdSelectOrgan($event)" />
          </el-form-item>
          <!--      <el-form-item>
            <el-input v-model="query.params.organId" placeholder="所属组织" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.organPath" placeholder="所属组织路径" />
          </el-form-item> -->
          <el-form-item>
            <SelectTree placeholder="设备类型" :props="props" :options="optionData" :value="valueIdSelect"
              :clearable="isClearable" :accordion="isAccordion" @getValue="getValueSelect($event)" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.mac" placeholder="设备MAC" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.enable" clearable placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'DEVICE_ADD'" type="success" icon="el-icon-plus" size="mini"
              @click="handleAdd">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'DEVICE_BATCH_EDIT'" type="info" icon="el-icon-edit" size="mini"
              @click="batchEdit">批量修改</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'DEVICR_BATCH_IMPORT'" type="success" icon="el-icon-upload2" size="mini"
              @click="toBatchImport">批量导入</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-download" size="mini" @click="downloadFile">模板下载</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
        ref="multipleTable" @select="selectOrganTable" @select-all="selectOrganAllTable"
        @selection-change="handleSelectionChange" type="selection" center>
        <!--    <el-table-column align="center" label="序号" width="50" type="selection">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column> -->
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="设备编码" width="140">
          <template slot-scope="scope">
            {{ scope.row.deviceCode }}
          </template>
        </el-table-column>
        <el-table-column label="设备名称" width="140">
          <template slot-scope="scope">
            {{ scope.row.deviceName }}
          </template>
        </el-table-column>
        <el-table-column label="设备类型" width="140">
          <template slot-scope="scope">
            {{ scope.row.deviceTypeName }}
          </template>
        </el-table-column>
        <el-table-column label="所属组织" width="140">
          <template slot-scope="scope">
            {{ scope.row.organName }}
          </template>
        </el-table-column>
        <el-table-column label="分润方式" width="110" prop="enable" :formatter="profitSharingTypeFormat" />
        <!--  <el-table-column label="所属组织" width="110">
          <template slot-scope="scope">
            {{ scope.row.organId }}
          </template>
        </el-table-column>
        <el-table-column label="所属组织路径" width="110">
          <template slot-scope="scope">
            {{ scope.row.organPath }}
          </template>
        </el-table-column> -->
        <el-table-column label="设备MAC" width="140">
          <template slot-scope="scope">
            {{ scope.row.mac }}
          </template>
        </el-table-column>
        <el-table-column label="是否生效" width="110" prop="enable" :formatter="enableFormat" />
        <el-table-column label="生成者" width="110">
          <template slot-scope="scope">
            {{ scope.row.createBy }}
          </template>
        </el-table-column>
        <!--         <el-table-column label="更新者" width="110">
          <template slot-scope="scope">
            {{ scope.row.updateBy }}
          </template>
        </el-table-column> -->
        <el-table-column label="生成日期" width="160">
          <template slot-scope="scope">
            {{ scope.row.createDate }}
          </template>
        </el-table-column>
        <!--     <el-table-column label="更新日期" width="160">
          <template slot-scope="scope">
            {{ scope.row.updateDate }}
          </template>
        </el-table-column> -->
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作" width="250">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSet" class="el-tag el-tag--primary el-tag--mini" v-has="'DEVICE_SELECT_SHARED'"
              style="cursor: pointer;" @click="queryShared(scope.$index, scope.row)">
              分润信息
            </span>
            <span v-if="!scope.row.isSet" class="el-tag el-tag--success el-tag--mini" v-has="'DEVICE_SELECT_SHARED'"
              style="cursor: pointer;" @click="toBindMerchant(scope.$index, scope.row)">
              追加设备合伙
            </span>
            <span v-if="!scope.row.isSet" class="el-tag el-tag--success el-tag--mini" v-has="'DEVICE_SELECT_SHARED'"
              style="cursor: pointer;" @click="toBindDevAisleMerchant(scope.$index, scope.row)">
              追加设备货道合伙
            </span>
            <span v-if="!scope.row.isSet" class="el-tag el-tag--success el-tag--mini" v-has="'DEVICE_SELECT_SHARED'"
              style="cursor: pointer;" @click="handleQueryDeviceStockCount(scope.$index, scope.row)">
              查看设备货道
            </span>
            <span class="el-tag el-tag--info el-tag--mini" v-has="'DEVICE_EDIT'" style="cursor: pointer;"
              @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet ? '保存' : "修改" }}
            </span>
            <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini" v-has="'DEVICE_DEL'"
              style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="deviceRules" ref="userForm">
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="form.deviceCode" placeholder="设备编码" auto-complete="off" />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="设备名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="设备类型" prop="deviceType">
            <SelectTree id="id" :prop="deviceType" placeholder="设备类型" :props="props" :options="optionData"
              :value="valueId" :clearable='false' @getValue="getValue($event)" />
          </el-form-item>
          <el-form-item label="所属组织" prop="organ">
            <SelectTree placeholder="所属组织" :props="organProps" :options="organOptionData" :clearable='false'
              :value="organvalueId" @getValue="getOrganValue($event)" />
          </el-form-item>
          <el-form-item label="分润方式">
            <el-select v-model="form.profitSharingType" placeholder="分润方式" style="width:23%">
              <el-option v-for="item in query.profitSharingTypeOptions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备MAC">
            <el-input v-model="form.mac" placeholder="设备MAC" auto-complete="off" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="form.enable" clearable placeholder="是否生效" style="width:100%">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-preventReClick type="primary" :loading="insetrAndEditButton" @click="handleEditSave('userForm')">确
            定</el-button>
        </div>
      </el-dialog>
      <!--分润弹框-->
      <el-dialog title="分润信息" :visible.sync="dialogFormVisibleShared">
        <!-- table 表格 -->
        <el-table :data="sharedlist" v-loading="sharelistLoading" row-key="index" element-loading-text="给我一点时间" border fit
          highlight-current-row height="350" ref="multipleTable" @select="selectSharedTable"
          @select-all="selectSharedAllTable" @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column label="组织" prop="organName" align="center" />
          <el-table-column label="商户" prop="merchantName" align="center" />
          <el-table-column label="合伙方式" width="110" prop="type" :formatter="cooperationMode" align="center" />
          <el-table-column label="是否生效" prop="enable" align="center" :formatter="enableFormat" />
          <el-table-column label="分润比例 (%)" prop="profitSharingRate" align="center" />
          <el-table-column align="center" prop="created_at" label="操作" width="100">
            <template slot-scope="scope">
              <span class="el-tag el-tag--info el-tag--mini" style="cursor: pointer;"
                @click="toEditShared(scope.$index, scope.row)">
                修改
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <!--修改分润弹框-->
      <el-dialog title="编辑分润信息" :visible.sync="dialogFormVisibleEditShared" width="30%">
        <el-form :model="sharedform" ref="sharedorm">
          <el-form-item label="组织">
            <el-input v-model="sharedform.organName" :disabled="true" placeholder="组织" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商户">
            <el-input v-model="sharedform.merchantName" :disabled="true" placeholder="组织" auto-complete="off" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="sharedform.enable" clearable placeholder="是否生效" style="width:100%">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分润比例 (%)">
            <el-input v-model="sharedform.profitSharingRate" show-word-limit placeholder="组织" auto-complete="off"
              width="100" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleEditShared = false">取 消</el-button>
          <el-button v-preventReClick type="primary" @click="doEditShared('sharedorm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--批量修改框-->
      <el-dialog title="批量修改" :visible.sync="dialogFormVisibleBatchEdit" width="30%">
        <el-form :model="batchEditform" :rules="batchEditRules" ref="batchEditform">
          <el-form-item label="设备类型" required>
            <SelectTree id="id" :prop="deviceType" placeholder="设备类型" :props="props" :options="optionData"
              :clearable='false' @getValue="getValueBatchEdit($event)" />
          </el-form-item>
          <el-form-item label="所属组织" required>
            <SelectTree placeholder="所属组织" :props="organProps" :options="organOptionData" :clearable='false'
              @getValue="getOrganValueBatchEdit($event)" />
          </el-form-item>
          <el-form-item label="分润方式" required>
            <el-select v-model="batchEditform.profitSharingType" placeholder="分润方式">
              <el-option v-for="item in query.profitSharingTypeOptions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否生效" prop="enable" required>
            <el-select v-model="batchEditform.enable" placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleBatchEdit = false">取 消</el-button>
          <el-button v-preventReClick type="primary" :loading="batchEditButton" @click="batchEditSave('batchEditform')">确
            定</el-button>
        </div>
      </el-dialog>
      <!--批量导入框-->
      <el-dialog title="批量导入" :visible.sync="dialogFormVisibleBatchImport" width="30%">
        <el-form :model="batchImportform" :rules="batchImportRules" ref="batchImportform">
          <el-form-item label="设备类型" required>
            <SelectTree id="id" :prop="deviceType" placeholder="设备类型" :props="props" :options="optionData"
              :clearable='false' @getValue="getValueBatchImport($event)" />
          </el-form-item>
          <el-form-item label="所属组织" required>
            <SelectTree placeholder="所属组织" :props="organProps" :options="organOptionData" :clearable='false'
              @getValue="getOrganValueBatchImport($event)" />
          </el-form-item>
          <el-form-item label="分润方式" required>
            <el-select v-model="batchImportform.profitSharingType" placeholder="分润方式">
              <el-option v-for="item in query.profitSharingTypeOptions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否生效" prop="enable" required>
            <el-select v-model="batchImportform.enable" placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择文件" required>
            <el-upload class="upload-demo" ref="upload"
              action="http://127.0.0.1:8765/device.controller/Device/importDevice" :on-success="uploadchange" :limit="1"
              :auto-upload="false" :data="batchImportform" :on-change="fileOnChange">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能选择 xls 或 xlsx 格式的文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleBatchImport = false">取 消</el-button>
          <el-button v-preventReClick type="primary" :loading="batchImportButton"
            @click="batchImportSave('batchImportform')">确 定</el-button>
        </div>
      </el-dialog>

      <!--绑定商户弹框-->
      <el-dialog title="合伙商户" :visible.sync="dialogFormVisibleSDeviceMerchant">
        <!-- table 表格 -->
        <el-table :data="deviceMerchantList" v-loading="deviceMerchantLoading" row-key="index"
          element-loading-text="给我一点时间" border fit highlight-current-row height="350" ref="multipleTable"
          @select="selectSharedTable" @select-all="selectSharedAllTable" @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column label="商户" prop="name" align="center" />
          <el-table-column label="默认分润比例 (%)" prop="profitSharingRate" align="center" />
          <el-table-column label="绑定状态" v-if="bindStatusShoW" align="center" prop="bindStatus"
            :formatter="bindStatusFormat" />
          <el-table-column label="合伙方式" prop="cooperationMode" :formatter="cooperationMode2" align="center" />
          <el-table-column align="center" prop="created_at" label="操作" width="100">
            <template slot-scope="scope">
              <span class="el-tag el-tag--info el-tag--danger" v-if="merbindShoW" style="cursor: pointer;"
                @click="doBindMerchant(scope.$index, scope.row)">
                {{ scope.row.deviceId ? '解除绑定' : "绑定" }}
              </span>
              <span v-if="aislebindShoW" class="el-tag el-tag--info el-tag--danger" style="cursor: pointer;"
                @click="toBindDevAisle(scope.$index, scope.row)">
                绑定货道
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>



      <!--设备货道table-->

      <!--     <el-dialog title="设备货道信息" :visible.sync="dialogFormVisibleDeviceAisle" width="45%">
        <div class="filter-container">
        </div>
  
        <el-table :data="deviceAisleList" v-loading="deviceAisleLoading" row-key="id" element-loading-text="给我一点时间" border fit highlight-current-row height="375" style="width: 100%" ref="multipleTableAisle" @select="selectDevAisleTable" @select-all="selectDevAisleTable" @selection-change="handleSelectionChange" >
            <el-table-column label="序号" prop="index" align="center" type="selection" />
          <el-table-column label="货道名称" prop="aisleName" align="center"/>
          <el-table-column label="绑定状态" prop="status" align="center" :formatter="goodsAisleStatus" />
        </el-table>
          <div slot="footer" class="dialog-footer">
          <el-button type="danger" :loading="doBindDevAisleMerchantButton" @click="doBindDevAisleMerchant()">绑定</el-button>
        </div>
       
        <div class="pagination-container">
          <el-pagination background @size-change="deviceAislehandleSizeChange" @current-change="deviceAislehandleCurrentChange" :current-page="deviceAisleCurrentPage" :page-sizes="[5,10,20, 30, 40,1000,9999]" :page-size="deviceAislePageSize" layout="total, sizes, prev, pager, next, jumper" :total="deviceAisletotal">
          </el-pagination>
        </div>
      </el-dialog>
 -->


      <el-dialog title="设备货道列表" :visible.sync="dialogFormVisibleDeviceStock">

        <div class="block">
          <el-table v-loading="listLoading" :data="deviceStockList" element-loading-text="Loading" border fit
            highlight-current-row>
            <el-table-column align="center" label="序号" width="95">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>

            <el-table-column label="模板编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.templateId }}
              </template>
            </el-table-column>
            <el-table-column label="所属机构" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.organId }}
              </template>
            </el-table-column>
            <el-table-column label="设备编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.deviceId }}
              </template>
            </el-table-column>
            <el-table-column label="设备编码" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.deviceCode }}
              </template>
            </el-table-column>
            <el-table-column label="控制板号" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.ctrlBoard }}
              </template>
            </el-table-column>
            <el-table-column label="控制指令" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.ctrlCmd }}
              </template>
            </el-table-column>
            <el-table-column label="货道状态；1:正常, 2:停用,3:异常" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.status }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.createBy }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.updateBy }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.createDate }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.updateDate }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.remark }}
              </template>
            </el-table-column>
            <el-table-column label="模板项编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.templateItemId }}
              </template>
            </el-table-column>
            <el-table-column label="货道名称" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.aisleName }}
              </template>
            </el-table-column>
            <el-table-column label="货道类型，0：弹簧，1：履带, 2：格子锁" width="110">
              <template slot-scope="scope">
                {{ scope.row.da.aisleType }}
              </template>
            </el-table-column>

            <el-table-column label="机器编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.deviceId }}
              </template>
            </el-table-column>
            <el-table-column label="货道编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.aisleId }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsId }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsName }}
              </template>
            </el-table-column>
            <el-table-column label="库存" width="110">
              <template slot-scope="scope">
                {{ scope.row.stockCount }}
              </template>
            </el-table-column>
            <el-table-column label="库存容量" width="110">
              <template slot-scope="scope">
                {{ scope.row.printCount }}
              </template>
            </el-table-column>
            <el-table-column label="商品价格" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsPrice }}
              </template>
            </el-table-column>
            <el-table-column label="商品主图片" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsImg }}
              </template>
            </el-table-column>
            <el-table-column label="商品成本" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsCost }}
              </template>
            </el-table-column>
            <el-table-column label="过期时间" width="110">
              <template slot-scope="scope">
                {{ scope.row.expirationTime }}
              </template>
            </el-table-column>
            <el-table-column label="商品优惠价" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsDiscountPrice }}
              </template>
            </el-table-column>
            <el-table-column label="排序" width="110">
              <template slot-scope="scope">
                {{ scope.row.sort }}
              </template>
            </el-table-column>
            <el-table-column label="是否热销,0:否，1:是" width="110">
              <template slot-scope="scope">
                {{ scope.row.isHot }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.createBy }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.updateBy }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.createDate }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.updateDate }}
              </template>
            </el-table-column>
            <el-table-column label="" width="110">
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
            <el-table-column label="删除标识" width="110">
              <template slot-scope="scope">
                {{ scope.row.isDeleted }}
              </template>
            </el-table-column>
            <el-table-column label="所属机构" width="110">
              <template slot-scope="scope">
                {{ scope.row.organId }}
              </template>
            </el-table-column>
            <el-table-column label="所属组织路径" width="110">
              <template slot-scope="scope">
                {{ scope.row.organPath }}
              </template>
            </el-table-column>


            <el-table-column align="center" prop="created_at" label="操作" width="200">
              <template slot-scope="scope">
                <span class="el-tag el-tag--info el-tag--mini" style="cursor: pointer;"
                  @click="handleEdit(scope.$index, scope.row)">
                  {{ scope.row.isSet ? '保存' : "修改" }}
                </span>
                <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;"
                  @click="handleDelete(scope.$index, scope.row)">
                  删除
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="block">
          <el-pagination :current-page="query.deviceStock.currentPage" :page-sizes="[10, 20, 30, 40]"
            :page-size="query.deviceStock.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="query.deviceStock.total" @size-change="handleDeviceStockSizeChange"
            @current-change="handleDeviceStockCurrentChange" />
        </div>

      </el-dialog>

      <!--设备货道绑定情况弹框-->
      <el-dialog title="设备货道绑定情况" :visible.sync="dialogFormVisibleDevAisle">
        <el-tree ref="tree" v-loading="devAisleLoading" element-loading-text="Loading" :data="devAisleList"
          :default-checked-keys="defaultSelectedNodes" :default-expand-all="false" :props="defaultProps"
          :check-strictly="false" show-checkbox node-key="templateItemId" highlight-current />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleDevAisle = false">取 消</el-button>
          <el-button type="primary" :loading="doBindDevAisleMerchantButton" @click="doBindDevAisleMerchant">确
            定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { querySubordinateOrgan } from '@/api/Organ'
import { getList, doDelete, doEdit, queryDeviceList, querySharedList, doEditShared, batchEdit, getMerchantList, bindMerchant, queryAllDeviceAisleBindSituation, bindDeviceAisleMerchant } from '@/api/device/'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode, getCurrentTimeYYYY_MM_dd_HH_mm_ss } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'
import preventReClick from '@/utils/preventReClick' //防多次点击，重复提交
import { queryCount as queryDeviceStockCount, queryStockPagination } from '@/api/deviceStock/'
import { getDictionaryGroup } from '@/api/dictionary'
export default {

  data() {
    return {
      profitSharingRate: '',
      bindMerchantId: '',
      bindStatusShoW: true,
      merbindShoW: false,
      aislebindShoW: false,
      dialogFormVisibleDeviceStock: false,
      doBindDevAisleMerchantButton: false,
      goodsAisleStatusOptions: [],
      devAisleArray: null,
      dialogFormVisibleDeviceAisle: false,
      deviceAisleCurrentPage: 1,
      deviceAislePageSize: 10,
      deviceAisletotal: 0,
      deviceAisleLoading: true,
      deviceAisleList: null,
      deviceAisleQuery: { params: { deviceId: '' }, },
      defaultProps: {
        children: 'children',
        label: 'aisleName',
        url: 'url'
      },
      defaultSelectedNodes: [],
      devAisleList: null,
      devAisleLoading: true,
      deviceMerchantList: null,
      deviceMerchantLoading: false,
      deviceMerchantListQuery: {
        deviceId: '',
        organPath: '',
      },
      merchantProps: {
        children: 'children',
        label: function (data, node) {
          console.log(node);
          return data.name + '   ( 默认比例：' + data.id + ')';
        },
      },
      merchantSelectedNodes: [],
      merchantList: null,
      merchantLoading: true,
      fielStatus: false,
      sharelistLoading: true,
      shareListQuery: {
        deviceId: '',
        enable: '',
      },
      sharedlist: null,
      shared: {
        list: false,
        add: false,
        chart: false
      },
      organArray: null,
      list: null,
      deviceStockList: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      dialogFormVisibleShared: false,
      dialogFormVisibleEditShared: false,
      dialogFormVisibleBatchEdit: false,
      dialogFormVisibleBatchImport: false,
      dialogFormVisibleDevAisle: false,
      dialogFormVisibleSDeviceMerchant: false,
      addForVisible: false,
      valueIdSelect: {}, // 初始ID（可选）
      valueId: {}, // 初始ID（可选）
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      supplierOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      organQueryModel: 'selfAndSub',
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      optionData: [],
      organvalueId: {}, // 初始ID（可选）
      organProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织'
        // disabled:true
      },
      organOptionData: [],
      valueId: {}, // 初始ID（可选）
      form: {
        id: '',
        deviceCode: '',
        deviceName: '',
        organId: '',
        organPath: '',
        type: '',
        mac: '',
        enable: '',
        remark: '',
        profitSharingType: ''
      },

      sharedform: {
        id: '',
        profitSharingRate: 0,
        enable: '',
        organName: '',
        merchantName: '',
        deviceId: ''
      },
      batchEditform: {
        organId: '',
        organPath: '',
        enable: '',
        deviceTypeCode: '',
        profitSharingType: ''
      },
      batchImportform: {
        organId: '',
        organPath: '',
        enable: '',
        type: '',
        profitSharingType: ''
      },
      deviceRules: {
        deviceCode: [{ required: true, message: '请输入设备编码', trigger: 'blur' },

        ],
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' },]
      },
      batchEditRules: {
        enable: [{ required: true, message: '请选择是否生效', trigger: 'blur' },]

      },
      batchImportRules: {
        enable: [{ required: true, message: '请选择是否生效', trigger: 'blur' },]

      },
      batchEditButton: false,
      insetrAndEditButton: false,
      batchImportButton: false,
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          deviceCode: '', //设备编码
          deviceName: '', //设备名称
          organId: '', //所属组织
          type: '', //设备类型编号
          typeId: '', //设备类型id
          mac: '', //设备MAC
          enable: '', //是否生效
          createBy: '', //生成者
          updateBy: '', //更新者
          createDate: '', //生成日期
          updateDate: '', //更新日期
          remark: '', //备注
        },
        merchantParams: {

        },
        deviceStock: {
          total: 5,
          currentPage: 1,
          pageSize: 10,
          deviceId: '',
          organId: '',
          organPath: ''
        },
        timeValue: '',
        enableOptions: [{
          value: 0,
          label: '否'
        }, {
          value: 1,
          label: '是'
        }],
        profitSharingTypeOptions: [{
          value: 0,
          label: '默认'
        }, {
          value: 1,
          label: '上级不分润'
        }],
        value: ''
      }
    }
  },
  created() {
 
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.initDeviceTypeTree();
    this.handleBuildCooperationModeOptions();
    this.handleBuildGoodsAisleStatusOptions();
    this.fetchData();
  },
  methods: {


    doBindDevAisleMerchant() {
      const checkedList = this.$refs.tree.getCheckedNodes()
      const halfCheckList = this.$refs.tree.getHalfCheckedNodes()
      const batchModify = []

      const allChecked = []

      for (let i = 0; i < checkedList.length; i++) {
        allChecked.push(checkedList[i])
      }

      for (let i = 0; i < halfCheckList.length; i++) {
        allChecked.push(halfCheckList[i])
      }

      for (let i = 0; i < allChecked.length; i++) {
        const devAisleMerchantList = {}
        devAisleMerchantList['aisleId'] = allChecked[i].templateItemId
        devAisleMerchantList['deviceId'] = this.deviceAisleQuery.params.deviceId;
        devAisleMerchantList['merchantId'] = this.bindMerchantId
        devAisleMerchantList['profitSharingRate'] = this.profitSharingRate
        devAisleMerchantList['organId'] = getOrganId()
        devAisleMerchantList['organPath'] = getOrganPath()



        batchModify.push(devAisleMerchantList)
      }

      console.log(batchModify)
      this.doBindDevAisleMerchantButton = true;

      bindDeviceAisleMerchant({ deviceId: this.deviceAisleQuery.params.deviceId, merchantId: this.bindMerchantId, profitSharingRate: this.profitSharingRate }, batchModify).then(response => {
        console.log(response)
        const data = response.data
        if (data.status < 200 && data.status >= 1) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.dialogAssignOrganFormVisible = false
        } else if (data.status === 403) {
          this.$message({
            type: 'warning',
            message: data.description
          })
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }

        this.doBindDevAisleMerchantButton = false;
      })
    },


    //保存选中记录
    selectDevAisleTable(selection, row) {
      this.devAisleArray = selection;
    },
    //保存所有选中记录
    selectDevAisleTable(selection) {
      this.devAisleArray = selection;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleBuildGoodsAisleStatusOptions() {
      getDictionaryGroup({ sys: 1, bigType: "GoodsAisleStatus", organId: getOrganId() }).then(response => {
        const data = response.data
        let goodsAisleStatusOptions = [];
        for (let i = 0; i < data.length; i++) {

          let option = {}
          option['value'] = data[i].value
          option['label'] = data[i].desc
          goodsAisleStatusOptions.push(option)
        }
        this.goodsAisleStatusOptions = goodsAisleStatusOptions
      })

    },
    goodsAisleStatus(row, column) {
      let label = ''
      for (let i = 0; i < this.goodsAisleStatusOptions.length; i++) {
        if ('' + row.status === this.goodsAisleStatusOptions[i].value) {
          return this.goodsAisleStatusOptions[i].label
        }

      }
      return label

    },

    toBindDevAisleMerchant(index, row) {
      this.deviceMerchantListQuery.cooperationMode = 2;
      this.deviceAisleQuery.params.deviceId = row.id;
      this.dialogFormVisibleSDeviceMerchant = true
      this.aislebindShoW = true;
      this.merbindShoW = false;
      this.bindStatusShoW = false;
      this.fetchDeviceMerchantData(row.id);

    },

    handleQueryDeviceStockCount(index, row) {

      queryDeviceStockCount({}, getOrganId(), row.id).then(response => {

        let data = response.data
        if (data) {//设备已创建货道了

          //查询设备货道
          this.query.deviceStock.deviceId = row.id
          this.query.deviceStock.organPath = null
          this.handleQueryDeviceStockPagiation(this.query.deviceStock)

        } else {

          //1.弹出设备类型所对应的设备货道模板

          this.$confirm('设备还没有初始化货道，是否需要创建?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {

            this.$message({
              type: 'info',
              message: '操作已取消'
            })

          }).catch(() => {

            //弹出设备类型所对应的设备货道模板
            this.query.deviceStock.deviceId = row.id
            this.query.deviceStock.organId = row.organId
            this.handleQueryDeviceStockPagiation(this.query.deviceStock)

          })
        }
      });
    },

    handleQueryDeviceStockPagiation(deviceStockParams) {

      this.dialogFormVisibleDeviceStock = true
      this.listLoading = true
      queryStockPagination(
        deviceStockParams,
        this.query.deviceStock.currentPage,
        this.query.deviceStock.pageSize

      ).then(response => {

        const data = response.data
        this.query.deviceStock.total = data.totalCount
        this.query.deviceStock.pageSize = data.pageSize
        this.query.deviceStock.currentPage = data.currentPage
        this.deviceStockList = data.entities
        this.listLoading = false
      })
    },
    handleDeviceStockSizeChange(val) {
      this.query.deviceStock.pageSize = val
      this.query.deviceStock.currentPage = 1
      this.handleQueryDeviceStockPagiation(this.query.deviceStock)
    },
    handleDeviceStockCurrentChange(val) {
      this.query.deviceStock.currentPage = val
      this.handleQueryDeviceStockPagiation(this.query.deviceStock)

    },
    toBindDevAisle(index, row) {
      this.bindMerchantId = row.id;
      this.profitSharingRate = row.profitSharingRate;
      this.deviceAisleQuery.params.merchantId = row.id;
      this.dialogFormVisibleDevAisle = true;
      this.doBindDevAisleMerchantButton = false;
      this.fetchDeviceAisleData();
      /*  this.doBindDevAisleMerchantButton=false;
         this.dialogFormVisibleDeviceAisle = true
         this.fetchDeviceAisleData();*/

    },

    fetchDeviceAisleData() {
      if (this.deviceAisleQuery.params.deviceId == '' || this.deviceAisleQuery.params.deviceId == '') {
        this.$message({
          type: 'warning',
          message: 'deviceId为null !'
        })
        return;
      }
      this.devAisleLoading = true
      queryAllDeviceAisleBindSituation(this.deviceAisleQuery.params).then(response => {
        this.devAisleList = response.data

        const devAisleAry = []

        for (let i = 0; i < this.devAisleList.length; i++) {
          if (this.devAisleList[i].merchantId != null && this.devAisleList[i].merchantId != '') {

            devAisleAry.push(this.devAisleList[i].templateItemId)
          }
        }
        this.defaultSelectedNodes = devAisleAry
        this.devAisleLoading = false
      })
    },


    fetchDevAisleMerchantData(deviceId) {
      this.deviceMerchantListQuery.deviceId = deviceId;
      if (!this.deviceMerchantListQuery.organPath) {
        this.deviceMerchantListQuery.organPath = getOrganPath()
      }
      this.devAisleMerchantLoading = true
      getMerchantList(this.deviceMerchantListQuery, 1, 50).then(response => {
        console.log(response)
        this.devAisleMerchantList = response.data.entities

        const devAisleMerchantAry = []

        for (let i = 0; i < this.devAisleMerchantList.length; i++) {
          if (this.devAisleMerchantList[i].merchantId) {
            devAisleMerchantAry.push(this.devAisleMerchantList[i].id)
          }
        }
        this.defaultSelectedNodes = devAisleMerchantAry
        this.devAisleMerchantLoading = false
      })
    },

    deviceAislehandleSizeChange(val) {
      this.deviceAisleCurrentPage = 1
      this.deviceAislePageSize = val
      this.fetchdeviceAisleData()

    },
    deviceAislehandleCurrentChange(val) {
      this.deviceAisleCurrentPage = val
      this.fetchdeviceAisleData()


    },

    handleBuildCooperationModeOptions() {
      getDictionaryGroup({ sys: 1, bigType: "cooperationMode", organId: getOrganId() }).then(response => {
        const data = response.data
        let cooperationModeOptions = [];
        for (let i = 0; i < data.length; i++) {

          let option = {}
          option['value'] = data[i].value
          option['label'] = data[i].desc
          cooperationModeOptions.push(option)
        }
        this.query.cooperationModeOptions = cooperationModeOptions
      })

    },
    cooperationMode(row, column) {
      let label = ''
      for (let i = 0; i < this.query.cooperationModeOptions.length; i++) {
        if ('' + row.merchantCooperationMode === this.query.cooperationModeOptions[i].value) {
          return this.query.cooperationModeOptions[i].label
        }

      }
      return label

    },

    cooperationMode2(row, column) {
      let label = ''
      for (let i = 0; i < this.query.cooperationModeOptions.length; i++) {
        if ('' + row.cooperationMode === this.query.cooperationModeOptions[i].value) {
          return this.query.cooperationModeOptions[i].label
        }

      }
      return label

    },

    bindStatusFormat(row, column) {
      if (row.deviceId == null || row.deviceId == '') {
        return '未绑定'
      } else {
        return '已绑定'
      }
    },

    fetchDeviceMerchantData(deviceId) {
      this.deviceMerchantListQuery.deviceId = deviceId;
      if (!this.deviceMerchantListQuery.organPath) {
        this.deviceMerchantListQuery.organPath = getOrganPath()
      }
      this.deviceMerchantLoading = true
      getMerchantList(this.deviceMerchantListQuery, 1, 50).then(response => {
        const data = response.data
        this.deviceMerchantList = data.entities
        this.deviceMerchantLoading = false
      })
    },
    doBindMerchant(index, row) {

      var mesName = ''
      if (row.deviceId == null || row.deviceId == '') {
        mesName = '绑定'
      } else {
        mesName = '解除绑定'
      }
      this.$confirm('是否确定 [ ' + mesName + ' ] 操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.deviceMerchantLoading = true
        bindMerchant({
          deviceId: this.deviceMerchantListQuery.deviceId,
          organId: getOrganId(),
          organPath: getOrganPath(),
        }, row).then(response => {
          const data = response.data
          if (data.status == 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchDeviceMerchantData(this.deviceMerchantListQuery.deviceId);

          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
          this.deviceMerchantLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })


    },

    toBindMerchant(index, row) {
      this.deviceMerchantListQuery.cooperationMode = 1;
      this.dialogFormVisibleSDeviceMerchant = true
      this.merbindShoW = true;
      this.aislebindShoW = false;
      this.bindStatus = true;
      this.fetchDeviceMerchantData(row.id);

    },
    fileOnChange(file, fileList) {
      this.fielStatus = true;
    },
    uploadchange(response, file, fileList) {
      console.log(response);

      if (response.status) {
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        this.fetchData();
        this.dialogFormVisibleBatchImport = false;
      } else {
        this.$message({
          type: 'info',
          message: '操作失败!'
        })
      }
    },
    //批量导入
    batchImportSave(formName) {

      if (this.batchImportform.type == null || this.batchImportform.type == '') {
        this.$message({
          type: 'warning',
          message: `请选择设备类型!`
        })
        return;
      }

      if (this.batchImportform.organId == null || this.batchImportform.organId == '') {
        this.$message({
          type: 'warning',
          message: `请选择组织!`
        })
        return;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.fielStatus) {
            this.$refs.upload.submit();
            this.batchImportButton = true;
          } else {
            this.$message({
              type: 'warning',
              message: '请先选择文件!'
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }

      })

    },
    getValueBatchImport(value) {
      this.batchImportform.type = value.deviceTypeCode;
    },
    getOrganValueBatchImport(value) {
      this.batchImportform.organId = value.id;
      this.batchImportform.organPath = value.organPath;
    },
    //打开批量导入
    toBatchImport() {

      this.batchImportform.profitSharingType = 0;
      this.batchImportform.enable = 1;
      this.batchImportButton = false;
      this.dialogFormVisibleBatchImport = true;
      this.$refs.upload.clearFiles();
      this.fielStatus = false;

    },
    //下载
    downloadFile(downloadUrl) {
      var url = "http://127.0.0.1:8765/device.controller/Device/downloadDeviceTemplate";
      window.open(url, '_blank');
    },
    getValueBatchEdit(value) {
      this.batchEditform.deviceTypeCode = value.deviceTypeCode;
    },
    getOrganValueBatchEdit(value) {
      this.batchEditform.organId = value.id;
      this.batchEditform.organPath = value.organPath;
    },
    //批量修改保存
    batchEditSave(formName) {
      if (this.batchEditform.deviceTypeCode == null || this.batchEditform.deviceTypeCode == '') {
        this.$message({
          type: 'warning',
          message: `请选择设备类型!`
        })
        return;
      }

      if (this.batchEditform.organId == null || this.batchEditform.organId == '') {
        this.$message({
          type: 'warning',
          message: `请选择组织!`
        })
        return;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {

          this.$confirm('是否确定批量修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.batchEditButton = true;
            batchEdit({
              deviceList: JSON.stringify(this.organArray),
              enable: this.batchEditform.enable,
              organId: this.batchEditform.organId,
              organPath: this.batchEditform.organPath,
              deviceTypeCode: this.batchEditform.deviceTypeCode,
              profitSharingType: this.batchEditform.profitSharingType,
            }).then(response => {
              const data = response.data
              if (data.status == 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.fetchData();
                this.organArray = null;
                this.dialogFormVisibleBatchEdit = false;
              } else if (data.status == 403) {
                this.$message({
                  type: 'warning',
                  message: data.description
                })
              } else {
                this.$message({
                  type: 'info',
                  message: '操作失败!'
                })
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消修改'
            })
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑分润
    doEditShared(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          doEditShared(this.sharedform).then(response => {
            console.log(response)
            const data = response.data
            if (data.status) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchSharedData();
            } else if (data.status === 0) {
              this.$message({
                type: 'info',
                message: '分润比例总和不能超过100!'
              })
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisibleEditShared = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }

      })
    },
    // 打开编辑分润窗口
    toEditShared(index, row) {
      this.sharedform.id = row.id;
      this.sharedform.enable = row.enable;
      this.sharedform.profitSharingRate = row.profitSharingRate;
      this.sharedform.organName = row.organName;
      this.sharedform.merchantName = row.merchantName;
      this.sharedform.deviceId = row.deviceId;
      this.dialogFormVisibleEditShared = true

    },
    fetchSharedData() {
      this.sharelistLoading = true
      querySharedList(this.shareListQuery, 1, 50).then(response => {
        const data = response.data
        this.sharedlist = data.entities
        this.sharelistLoading = false
      })
    },
    //保存选中记录
    selectOrganTable(selection, row) {
      this.organArray = selection;
    },
    //保存所有选中记录
    selectOrganAllTable(selection) {
      this.organArray = selection;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    initDeviceTypeTree() {
      this.listLoading = true
      queryDeviceList({ organPath: getOrganPath() }).then(response => {
        console.log(response)
        const data = response.data
        this.optionData = handleBuildTreeDataStruct(data, 'id', 'parentId')
        this.listLoading = false
      })
    },

    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function (item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function () {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function (item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    getValue(value) {
      // this.valueId = value
      console.log(value.deviceTypeCode)
      this.form.type = value.id; //编号
      this.form.typeId = value.id; //id
    },
    getOrganValue(value) {
      this.form.organId = value.id;
      this.form.organPath = value.organPath;
    },
    getValueSelect(value) {
      if (value == null) {
        this.query.params.type = '';
      } else {
        this.valueIdSelect = value
        this.query.params.type = value.deviceTypeCode
      }
    },
    getValueIdSelectOrgan(value) {
      console.log(value)
      if (value == null) {
        this.query.params.organId = '';
      } else {
        this.query.params.organId = value.id;
      }
    },
    enableFormat(row, column) {
      if (row.enable === 0) {
        return '否'
      } else if (row.enable === 1) {
        return '是'
      }
    },
    profitSharingTypeFormat(row, column) {
      if (row.profitSharingType === 0) {
        return '默认'
      } else if (row.profitSharingType === 1) {
        return '上级不分润'
      }
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      this.insetrAndEditButton = false;
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.deviceCode = ''
      this.form.deviceName = ''
      this.form.mac = ''
      this.form.enable = 1
      this.form.createBy = ''
      this.form.updateBy = ''
      this.form.createDate = ''
      this.form.updateDate = ''
      this.form.remark = ''
      this.addForVisible = false
      this.valueId = '';
      this.form.profitSharingType = 0


    },
    // 编辑
    handleEdit(index, row) {
      this.insetrAndEditButton = false;
      console.log(index)
      console.log(row)
      this.form.id = row.id
      this.form.deviceCode = row.deviceCode
      this.form.deviceName = row.deviceName
      this.form.organId = row.organId
      this.form.organPath = row.organPath

      this.form.mac = row.mac
      this.form.enable = row.enable
      this.form.createBy = row.createBy
      this.form.updateBy = row.updateBy
      this.form.createDate = row.createDate
      this.form.updateDate = row.updateDate
      this.form.remark = row.remark
      this.form.profitSharingType = row.profitSharingType
      console.log(row.type)
      this.valueId = row.type
      this.form.type = row.type
      this.organvalueId = row.organId
      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'


    },
    // 批量编辑
    batchEdit(index, row) {

      if (this.organArray == null || this.organArray.length == 0) {
        this.$message({
          type: 'warning',
          message: `请选择设备!`
        })
      } else {
        console.log(this.organArray)
        this.batchEditButton = false;

        this.batchEditform.profitSharingType = 0;
        this.batchEditform.enable = 1;
        this.dialogFormVisibleBatchEdit = true;
      }



    },
    queryShared(index, row) {
      this.dialogFormVisibleShared = true
      this.shareListQuery.deviceId = row.id
      this.shareListQuery.enable = 1;
      this.fetchSharedData();
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status == 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave(formName) {

      if (this.form.type == null || this.form.type == '') {
        this.$message({
          type: 'warning',
          message: `请选择设备类型 !`
        })
        return;
      }

      if (this.form.organId == null || this.form.organId == '') {
        this.$message({
          type: 'warning',
          message: `请选择组织 !`
        })
        return;
      }


      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.insetrAndEditButton = true;
          doEdit(this.form).then(response => {
            debugger
            console.log(response)
            const data = response.data
            if (data.status) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData();
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }

      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}

</script>
